package org.javagenerate.generator.script.gen;

import java.util.HashSet;
import java.util.Set;

import org.javagenerate.generator.NamingUtils;
import org.javagenerate.generator.script.BasePatternGenerator;
import org.javagenerate.generator.script.ClassDef;
import org.javagenerate.generator.script.GenBeanDefinition;
import org.javagenerate.generator.script.PatternRef;

public class DtoDef extends ClassDef {

	public DtoDef(String classname, String patternName) {
		super(classname, patternName);
	}
	
	private Set<String> dependacies = new HashSet<String>();
	private String objectTypes = "";
	
	@Override
	public void addBeanDefiniation(GenBeanDefinition beanDefinition) {
		if (Character.isLowerCase(beanDefinition.getType().charAt(0))) {
			// denotes that this is a Bean based on this pattern, why else would
			// it be lower case?
			String baseName = NamingUtils.upperFirst(beanDefinition.getType());
			GenBeanDefinition thisDef = new GenBeanDefinition(beanDefinition.getName(), baseName + "DTO", beanDefinition.getOptions());
			
			String appendTs = baseName + "DTO";
			if (objectTypes.length() == 0) {
				objectTypes = appendTs;
			} else {
				if (!objectTypes.contains(appendTs)) {
					objectTypes += ", " + appendTs;
				}
			}
			// <AddressType extends AddressDef>
			super.addBeanDefiniation(thisDef);
			dependacies.add(beanDefinition.getType());
		} else {
			super.addBeanDefiniation(beanDefinition);
		}
	}

	@Override
	public void preWrite() {
		super.preWrite();
		
		BasePatternGenerator generator = PatternRef.getBasePatternGenerator(getPatternName());
		ClassDef interfaceDef = generator.getClass("interface");

		getImplements().add(interfaceDef.getClassName() +  (objectTypes.length() > 0 ? "<" + objectTypes + ">" : ""));

		for (String dependacy : dependacies) {
			generator = PatternRef.getBasePatternGenerator(dependacy);
			ClassDef classDef = generator.getClass("dto");
			getImports().add(classDef.getPackageName() +"."+ classDef.getClassName());
		}
	}
	

}
